package com.kly.pay.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.enums.CallBackResultEnum;
import com.kly.enums.PayTypeEnum;
import com.kly.pay.db.entity.POrderEntity;
import com.kly.util.HttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Map;


/**
 * 支付回调业务系统
 */
public abstract class AbstractCallBackSendService {

    private static Log logger = LogFactory.getLog(AbstractCallBackSendService.class);
    @Autowired
    HttpClient httpClient;

    /**
     * 抽象callback方法，具体的实现由各个类处理
     */
    public abstract <T> CallBackResult doCallBack(PayTypeEnum payTypeEnum, T t) throws Exception;

    public CallBackResult sendResult(String url, Map<String, String> bodyMap) throws Exception {

        if (CollectionUtils.isEmpty(bodyMap)) {
            logger.error("sendResultFailed,the request should not be empty,url:{}", url);
            new CallBackResult().setSuccess(false).setMsg("The request should not be empty");
        }
//        String json = JSON.toJSONString(bodyMap);
        String res = httpClient.postJsonData(url, bodyMap);
        if (StringUtils.isEmpty(res)) {
            logger.error("sendResultFailed,the result is empty,url:{} , json:{}, result:{}", url, JSONObject.toJSONString(bodyMap), res);
            return new CallBackResult().setSuccess(false).setMsg("The result is empty").setNotifyMsg(JSONObject.toJSONString(bodyMap));
        }
        JSONObject jsonObject = JSON.parseObject(res);

        return new CallBackResult().setSuccess("0".equals(jsonObject.getString("code") + "") || CallBackResultEnum.SUCCESS.getCode().equals(jsonObject.getString("ret_code")))
                .setMsg(null == jsonObject.getString("msg") ? jsonObject.getString("msg") : jsonObject.getString("ret_msg"))
                .setNotifyMsg(JSONObject.toJSONString(bodyMap)).setCallBackMsg(res);
    }

}
